package kr.hkit.summary_java.erp;

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import kr.hkit.myframework.db.ConnectionFactory;
import kr.hkit.myframework.db.DbUtil;

public class PrnCodeTitle extends JPanel {
	private JTable table;
	private Connection con = ConnectionFactory.getConnection();
	private ResultSet rs;
	private PreparedStatement pstmt;
	private JScrollPane scrollPane;

	/**
	 * Create the panel.
	 */
	public PrnCodeTitle() {
		initialize();
		try {
			inputDb();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		tableCellAlginAndWidth();
	}

	private void inputDb() throws SQLException {
		DefaultTableModel model = (DefaultTableModel) table.getModel();
		String sql = "select * from codetitle";
		pstmt = con.prepareStatement(sql);
		rs = pstmt.executeQuery();
		Object[] newRow = null;
		while (rs.next()) {
			newRow = new Object[] { rs.getInt(1), rs.getString(2) };
			model.addRow(newRow);
		}
		DbUtil.close(con);
		DbUtil.close(pstmt);
		DbUtil.close(rs);
	}

	private void initialize() {
		setLayout(new BorderLayout(0, 0));

		scrollPane = new JScrollPane();
		add(scrollPane, BorderLayout.NORTH);
		
		table = new JTable();
		table.setModel(new DefaultTableModel(new Object[][] {}, new String[] {
				"직책번호", "직책명" }));
		scrollPane.setViewportView(table);
	}
	
	private void tableCellAlginAndWidth() {
		DefaultTableCellRenderer dtcrCenter = new DefaultTableCellRenderer();
		dtcrCenter.setHorizontalAlignment(SwingConstants.CENTER);

		TableColumnModel cModel = table.getColumnModel();

		cModel.getColumn(0).setPreferredWidth(70);
		cModel.getColumn(0).setCellRenderer(dtcrCenter);

		cModel.getColumn(1).setPreferredWidth(70);
		cModel.getColumn(1).setCellRenderer(dtcrCenter);
	}
}
